<template>
	<view class="audio-page">
		<!-- 静态背景层 -->
		<view class="audio-bg"></view>
		<!-- 顶部操作栏 -->
		<view class="top-operate-bar">
			<view class="back-btn" @click="navigateBack">
				<u-icon name="arrow-left" size="28"></u-icon>
			</view>
			<view class="robot-entry" @click="toggleRobotChat">
				<image src="https://hjyqyh.oss-cn-beijing.aliyuncs.com/whitenoise/myHome/moodRobot.png"  class="robot-header-avatar"></image>
				<text class="robot-text">情感陪伴</text>
			</view>
		</view>
		
		<!-- 核心内容区 -->
		<view class="audio-content">
			<!-- 音频封面 -->
			<view class="audio-cover" :class="{'playing': isPlaying}">
				<image :src="currentAudio.coverUrl" mode="widthFix"></image>
			</view>
			
			<!-- 音频信息 -->
			<view class="audio-info">
				<view class="audio-title">{{currentAudio.title}}</view>
				<view class="audio-desc">{{moodName}} · {{currentAudio.duration}}</view>
			</view>
			
			<!-- 进度条 -->
			<view class="progress-bar">
				<text class="time current-time">{{formatTime(currentTime)}}</text>
				<view class="progress-container" @click="changeProgress">
					<view class="progress-bg"></view>
					<view class="progress-fill" :style="{'width': progress + '%'}"></view>
					<view class="progress-dot" :style="{'left': progress + '%'}"></view>
				</view>
				<text class="time total-time">{{currentAudio.duration}}</text>
			</view>
			<!-- 播放控制按钮 -->
			<view class="control-btns">
				<view @click="toggleLoop" class="cycle" :class="{'loop': isLoop}">
					<u-icon name="reload" color="white" size="28" ></u-icon>
				</view>
				<view class="btn prev-btn" @click="playPrev">
					<u-icon name="rewind-left" color="white" size="28" ></u-icon>
				</view>
				<view class="btn play-btn" @click="togglePlay">
					<u-icon 
					  :name="isPlaying ? 'error-circle' : 'play-right-fill'" 
					  color="white" 
					  size="35"
					></u-icon>
				</view>
				<view class="btn next-btn" @click="playNext">
					<u-icon name="rewind-right" color="white" size="28"></u-icon>
				</view>
				<view class="btn fav-btn"  @click="toggleFav"  >
					<p  class="love" :class="{'full': isFav}" >♥</p>  
				</view>
			</view>
			<!-- 同情绪推荐音频 -->
			<view class="related-audios" v-if="relatedAudios.length > 0">
				<view class="related-title">更多{{moodName}}推荐</view>
				<view class="related-list">
					<view class="related-item" v-for="(item, index) in relatedAudios" :key="index" @click="playRelated(item,index)">
						<image :src="item.coverUrl" mode="widthFix" style="width: 120rpx; height: 120rpx; border-radius: 50%;"></image>
						<view class="item-title">{{item.title}}</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 机器人聊天窗 -->
		<view class="robot-chat-window" v-if="isChatShow">
			<view class="chat-header">
				<image src="https://hjyqyh.oss-cn-beijing.aliyuncs.com/whitenoise/myHome/moodRobot.png" class="robot-header-avatar"></image>
				<view class="chat-header-title">情感机器人</view>
				<view class="close-chat" @click="toggleRobotChat">
					<u-icon name="close" color="white" size="28"></u-icon>
				</view>
			</view>
			
			<!-- 聊天内容区 - 使用单个数组维护所有消息 -->
			<view class="chat-content" ref="chatContent" scroll-y="true">
				<view 
					class="chat-item" 
					:class="{'robot-chat': item.isRobot, 'user-chat': !item.isRobot}"
					v-for="(item, idx) in chatMessages" 
					:key="idx"
				>
					<image 
						v-if="item.isRobot" 
						src="/static/robot-avatar.png" 
						mode="widthFix" 
						class="chat-avatar"
					></image>
					<view class="chat-bubble">
						<text>{{item.content}}</text>
					</view>
					<image 
						v-if="!item.isRobot" 
						src="/static/user-avatar.png" 
						mode="widthFix" 
						class="chat-avatar"
					></image>
				</view>
			</view>
			
			<!-- 聊天输入区 -->
			<view class="chat-input-area">
				<input 
					class="chat-input" 
					v-model="currentInput" 
					placeholder="输入想聊的内容..." 
					placeholder-style="color: rgba(150,150,150,0.8)"
					@confirm="sendChatMessage"
				/>
				<view class="send-btn" @click="sendChatMessage">
						<u-icon name="checkmark" color="white" size="24"></u-icon>
				</view>
			</view>
		</view>

		<!-- 聊天窗遮罩层 -->
		<view class="chat-mask" v-if="isChatShow" @click="toggleRobotChat"></view>
	</view>
</template>

<script>
import { getAudioListByMoodId } from '../../api/Audio';
import { collectMusic } from '../../api/User';
import { getUserAudioCollect } from '../../api/UserAudioCollect';
	export default {
		data() {
			return {
				moodName: '',
				moodId:0,
				isPlaying: false,
				currentTime: 0,
				progress: 0,
				isLoop: false,
				isFav: false,
				currentAudio: {
					id:"",
					coverUrl:"",
					title: '',
					duration: '',
					audioUrl: ''
				},
				currentIndex:0,
				relatedAudios: [],
				audioContext: null,
				isChatShow: false,
				currentInput: '',
				chatMessages: [] // 存储消息，{content: '消息内容', isRobot: true/false}
			};
		},
		onLoad(options) {
			this.moodName = options.moodName || '放松一下';
			this.moodId = options.moodId;
			this.getAudioListByMoodId().then(() => {
			    this.initAudio();
				this.getUserAudioCollect()
			  });
			// 初始化机器人欢迎消息
			this.chatMessages.push({
				content: `你好呀～我知道你现在是${this.moodName}状态，有什么想跟我聊的吗？`,
				isRobot: true
			});
		},
		onUnload() {
			if (this.audioContext) {
				this.audioContext.pause();
				this.audioContext = null;
			}
		},
		methods: {
			async getAudioListByMoodId(){
				const res =  await getAudioListByMoodId(this.moodId) 
				this.relatedAudios = res.data.moodAudio
				this.currentAudio = res.data.moodAudio[0]
				console.log(res)
			},
			async getUserAudioCollect(){
				const res = await getUserAudioCollect()
				if (res.data) {
				    res.data.forEach(item => {
				      if (item.id === this.currentAudio.id && item.isCancel==0) {
				          this.isFav = true
				      }else{
						  this.isFav = false
					  }
				});
			}},
			initAudio() {
			  this.audioContext = uni.createInnerAudioContext();
			  this.audioContext.src = this.currentAudio.audioUrl.trim(); 
			  this.audioContext.loop = this.isLoop;
			  this.audioContext.onPlay(() => {
			    this.isPlaying = true;
			    console.log("音频开始播放");
			  });
			  
			  this.audioContext.onPause(() => {
			    this.isPlaying = false;
			    console.log("音频暂停");
			  });
			  this.audioContext.onTimeUpdate(() => {
			    this.currentTime = this.audioContext.currentTime;
			    if (this.audioContext.duration) {
			      this.progress = (this.currentTime / this.audioContext.duration) * 100;
			    }
			  });
			  this.audioContext.onError((err) => {
			    console.error("音频加载/播放失败：", err);
			    uni.showToast({
			      title: `播放失败：${err.errMsg}`,
			      icon: "none",
			      duration: 3000
			    });
			  });
			  this.audioContext.onCanplay(() => {
			    console.log("音频加载完成，可播放");
			    console.log("音频总时长：", this.audioContext.duration);
			  });
			},
			togglePlay() {
			  if (!this.audioContext) {
			    uni.showToast({ title: '音频未初始化', icon: 'none' });
			    return;
			  }
			  this.isPlaying ? this.audioContext.pause() : this.audioContext.play();
			},
			toggleLoop() {
				this.isLoop = !this.isLoop;
				this.audioContext.loop = this.isLoop;
				if(this.isLoop){
					this.currentAudio = this.relatedAudios[this.currentIndex]
					this.currentTime = 0;
					this.progress = 0;
					this.audioContext.src = this.currentAudio.audioUrl.trim();
					this.audioContext.play();
					uni.showToast({
						title:"开启循环播放"
					})
				}else{
					this.audioContext.pause();
					uni.showToast({
						title:"关闭循环播放",
						icon:'none'
					})
				}
			},
			toggleFav() {
				if(this.isFav){
					collectMusic(this.currentAudio.id).then(res=>{
						if(res.code==0){
							uni.showToast({
								title:"取消收藏",
								icon:'none'
							})
							this.isFav = false
						}else{
							uni.showToast({
								title:"取消收藏失败",
								icon:'none'
							})
						}
					})	
				}else{
					collectMusic(this.currentAudio.id).then(res=>{
						if(res.code==0){
							uni.showToast({
								title:"收藏成功",
							})
							this.isFav = true
						}else{
							uni.showToast({
								title:"收藏失败",
							})					
						}
					})
				}	
			},
			playPrev() {
				if(this.currentIndex>0){
					this.isLoop = false;
					this.audioContext.loop = this.isLoop;
					this.currentAudio = this.relatedAudios[this.currentIndex-1]
					this.currentIndex = this.currentIndex-1
					this.currentTime = 0;
					this.progress = 0;
					this.audioContext.src = this.currentAudio.audioUrl.trim();
					this.audioContext.play();
					uni.showToast({ title: '播放上一首', icon: 'none' });
				}else{
					uni.showToast({ title: '已经是第一首啦亲', icon: 'none' });
				}
			},
			playNext() {
				if(this.currentIndex<this.relatedAudios.length+1){
					this.isLoop = false;
					this.audioContext.loop = this.isLoop;
					this.currentAudio = this.relatedAudios[this.currentIndex+1]
					this.currentIndex = this.currentIndex+1
					this.currentTime = 0;
					this.progress = 0;
					this.audioContext.src = this.currentAudio.audioUrl.trim();
					this.audioContext.play();
					uni.showToast({ title: '播放下一首', icon: 'none' });
				}else{
					uni.showToast({ title: '已经是最后一首啦亲', icon: 'none' });
				}
				uni.showToast({ title: '播放下一首', icon: 'none' });
			},
			playRelated(item,index) {
				this.isLoop = false;
				this.audioContext.loop = this.isLoop;
				this.currentIndex = index;
				console.log(this.currentIndex)
				this.currentAudio = item;
				this.currentTime = 0;
				this.progress = 0;
				this.audioContext.src = this.currentAudio.audioUrl.trim();
				this.getUserAudioCollect()
				this.audioContext.play();
			},
			changeProgress(e) {
				const containerWidth = e.currentTarget.clientWidth;
				const clickLeft = e.touches[0].clientX - e.currentTarget.offsetLeft;
				this.progress = (clickLeft / containerWidth) * 100;
			},
			formatTime(seconds) {
				const min = Math.floor(seconds / 60);
				const sec = Math.floor(seconds % 60);
				return `${min.toString().padStart(2, '0')}:${sec.toString().padStart(2, '0')}`;
			},
			navigateBack() {
				uni.switchTab({
					url:"/pages/MoodSelect/moodSelect"
				})
			},

			// 聊天功能 
			toggleRobotChat() {
				this.isChatShow = !this.isChatShow;
			},

			// 发送消息核心方法
			async sendChatMessage() {
			  const inputVal = this.currentInput.trim();
			  if (!inputVal) return;
			  this.chatMessages.push({
			    content: inputVal,
			    isRobot: false
			  });
			  this.currentInput = '';
			  this.scrollToBottom();
			  this.chatMessages.push({
			    content: 'AI正在回复...',
			    isRobot: true,
			    isLoading: true
			  });
			  this.scrollToBottom();
			  const aiMsgIndex = this.chatMessages.length - 1; 
			  const encodedMsg = encodeURIComponent(inputVal);
			  const encodedMoodName = encodeURIComponent( this.moodName);
			  const eventSource = new EventSource(`http://localhost:8889/ai/generateStreamAsString?message=${encodedMsg}&moodName=${encodedMoodName}`);
			  eventSource.onmessage = (event) => { 
			    const chunk = event.data;
			    if (chunk === '[complete]') {
			      // 流结束：更新加载状态
			      this.$set(this.chatMessages, aiMsgIndex, {
			        ...this.chatMessages[aiMsgIndex],
			        isLoading: false
			      });
			      eventSource.close();
			      return;
			    }
			    this.$set(this.chatMessages, aiMsgIndex, {
			      content: this.chatMessages[aiMsgIndex].content === 'AI正在回复...' 
			        ? chunk 
			        : this.chatMessages[aiMsgIndex].content + chunk,
			      isRobot: true,
			      isLoading: true
			    });
			    this.scrollToBottom();
			  };
			  eventSource.onerror = (error) => {
			    console.error('连接错误:', error);
			    this.$set(this.chatMessages, aiMsgIndex, {
			      content: '网络异常，请检查网络连接后重试',
			      isRobot: true,
			      isError: true
			    });
			    eventSource.close();
			    this.scrollToBottom();
			  };
			},
			// 滚动到最新消息
			scrollToBottom() {
				this.$nextTick(() => {
					const chatContent = this.$refs.chatContent;
					if (chatContent) {
						chatContent.scrollTop = chatContent.scrollHeight;
					}
				});
			}
		}
	};
</script>

<style scoped>
	/* 基础样式 */
	.audio-page { width: 100vw; height: 100vh; overflow: hidden; position: relative; }
	.audio-bg { position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 0; 
		background-image: url("https://hjyqyh.oss-cn-beijing.aliyuncs.com/whitenoise/backgroundImg/backgroundImg.png"); }
	
	/* 顶部操作栏 */
	.top-operate-bar { position: absolute; top: 40rpx; left: 30rpx; right: 30rpx; z-index: 2; 
		display: flex; justify-content: space-between; align-items: center; }
	.robot-entry { display: flex; align-items: center; gap: 16rpx; 
		padding: 16rpx 28rpx; border-radius: 40rpx; backdrop-filter: blur(8rpx); }
	.robot-text { font-size: 28rpx; color: #fff; font-weight: 500; }
	
	/* 音频内容区 */
	.audio-content { position: relative; z-index: 1; width: 100%; height: 100%; 
		display: flex; flex-direction: column; align-items: center; justify-content: center; 
		padding: 0 30rpx 150rpx; box-sizing: border-box; }
	
	/* 音频封面 */
	.audio-cover { width: 280rpx; height: 280rpx; border-radius: 50%; overflow: hidden; 
		margin-bottom: 40rpx; box-shadow: 0 0 30rpx rgba(255,255,255,0.3); }
	.audio-cover image { width: 100%; height: 100%; object-fit: cover; }
	.audio-cover.playing { animation: rotate 10s linear infinite; }
	@keyframes rotate { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
	.cycle.loop{ animation: rotate 6s linear infinite;}
	/* 音频信息 */
	.audio-info { text-align: center; margin-bottom: 50rpx; }
	.audio-title { font-size: 36rpx; color: #fff; font-weight: 600; margin-bottom: 15rpx; }
	.audio-desc { font-size: 24rpx; color: rgba(255,255,255,0.8); }
	
	/* 进度条 */
	.progress-bar { width: 100%; display: flex; align-items: center; gap: 15rpx; margin-bottom: 60rpx; }
	.time { font-size: 22rpx; color: rgba(255,255,255,0.8); width: 80rpx; text-align: center; }
	.progress-container { flex: 1; height: 8rpx; background: rgba(255,255,255,0.2); 
		border-radius: 4rpx; position: relative; }
	.progress-fill { position: absolute; top: 0; left: 0; height: 100%; background: #fff; border-radius: 4rpx; }
	.progress-dot { position: absolute; top: 50%; transform: translate(-50%, -50%); 
		width: 20rpx; height: 20rpx; background: #fff; border-radius: 50%; }
	
	/* 控制按钮 */
	.love{color: white; font-size: 58rpx;}
	.love.full{color: red;}
	.control-btns { display: flex; align-items: center; gap: 40rpx; margin-bottom: 80rpx; }
	/* 推荐音频 */
	.related-audios { width: 100%; }
	.related-title { font-size: 28rpx; color: #fff; margin-bottom: 20rpx; }
	.related-list { display: flex; gap: 25rpx;  flex-wrap: wrap; /* 允许内容换行 */ overflow-x: auto; padding-bottom: 10rpx; }
	.related-list::-webkit-scrollbar { display: none; }
	.related-item { width: 20%; flex-shrink: 0; margin: 8rpx;}
	.related-item image { width: 100%; height: 180rpx; border-radius: 15rpx; margin-bottom: 15rpx; }
	.item-title { font-size: 22rpx; color: rgba(255,255,255,0.9); white-space: nowrap; 
		overflow: hidden; text-overflow: ellipsis; }
	
	/* 聊天窗口 */
	.robot-chat-window { position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); 
		width: 90%; max-width: 640rpx; height: 75%; max-height: 800rpx; background: rgba(15,15,25,0.95); 
		border-radius: 40rpx; z-index: 100; overflow: hidden; border: 2rpx solid rgba(195,207,255,0.5); }
	
	.chat-header { display: flex; align-items: center; gap: 20rpx; padding: 15rpx 32rpx; 
		background: rgba(30,30,50,0.8); border-bottom: 1rpx solid rgba(195,207,255,0.3); }
	.robot-header-avatar { width: 64rpx; height: 64rpx; border-radius: 50%; }
	.chat-header-title { flex: 1; font-size: 32rpx; color: #fff; font-weight: 500; }
	.close-chat { width: 56rpx; height: 56rpx; display: flex; align-items: center; justify-content: center; 
		border-radius: 50%; background: rgba(255,255,255,0.1); }
	
	/* 聊天内容区 - 关键修复：使用单个数组渲染所有消息 */
	.chat-content { width: 100%; height: calc(100% - 180rpx); padding: 32rpx 24rpx; 
		box-sizing: border-box; overflow-y: auto; -webkit-overflow-scrolling: touch; }
	.chat-content::-webkit-scrollbar { display: none; }
	
	.chat-item { display: flex; margin-bottom: 32rpx; max-width: 80%; animation: fadeIn 0.3s ease; }
	.robot-chat { align-self: flex-start; }
	.user-chat { flex-direction: row-reverse; align-self: flex-end; margin-left: auto; }
	.chat-avatar { width: 60rpx; height: 60rpx; border-radius: 50%; margin: 8rpx 16rpx 0; }
	.chat-bubble { padding: 24rpx 32rpx; border-radius: 30rpx; font-size: 26rpx; 
		line-height: 44rpx; color: #fff; white-space: pre-wrap; word-break: break-all; }
	.robot-chat .chat-bubble { background: rgba(195,207,255,0.3); border-bottom-left-radius: 8rpx; }
	.user-chat .chat-bubble { background: rgba(195,207,255,0.6); border-bottom-right-radius: 8rpx; }
	
	.chat-input-area { display: flex; align-items: center; gap: 16rpx; padding: 14rpx 32rpx; 
		background: rgba(30,30,50,0.8); border-top: 1rpx solid rgba(195,207,255,0.3); }
	.chat-input { flex: 1; height: 72rpx; background: rgba(255,255,255,0.1); border-radius: 36rpx; 
		padding: 0 32rpx; font-size: 26rpx; color: #fff; }
	.send-btn { width: 60rpx; height: 60rpx; background:rgba(195,207,255,0.3); border-radius: 50%; 
		display: flex; align-items: center; justify-content: center; }
	.send-btn .iconfont { font-size: 36rpx; color: #151525; }
	.send-btn.disabled .iconfont { color: rgba(255,255,255,0.5); }
	
	.chat-mask { position: fixed; top: 0; left: 0; width: 100vw; height: 100vh; 
		background: rgba(0,0,0,0.7); z-index: 99; backdrop-filter: blur(4rpx); }
	
	/* 简单动画 */
	@keyframes fadeIn { from { opacity: 0; transform: translateY(10rpx); } to { opacity: 1; } }
</style>
